package menu.lt.pers.menu;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.google.gson.Gson;
import menu.lt.pers.menu.Bean.RecipeClassResultBean;
import menu.lt.pers.menu.Bean.UserBean;
import menu.lt.pers.menu.dao.ResourceDao;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Fragment_kind extends Fragment {
    private ListView listView_tag;
    private GridView gridView_class;
    private List<RecipeClassResultBean.ResultBean> result;
    private int currentList = 0;
    private TextView tv_class;
    private List<HashMap<String, Object>> class_data;
    private MyListview myListview;
    private boolean login_state = false;
    private UserBean user;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_kind,container,false);
        initView(view);
        setListener();
        Log.i("Fragment_kind.onCreateView","即将开始获取数据...");
        new getData().execute();
        return view;
    }

    private void setListener() {
        listView_tag.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentList!=position){
                    currentList = position;
                    myListview.notifyDataSetChanged();
                    initData();
                    updateView();
                }
            }
        });



        gridView_class.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(),ClassActivity.class);
                Gson gson = new Gson();
                intent.putExtra("list", gson.toJson(result.get(currentList).getList()));
                intent.putExtra("index", position);
                if (login_state){
                    intent.putExtra("user",gson.toJson(user));
                }
                Log.i("gridView_class.setOnItemClickListener", "onItemClick: "+login_state);
                startActivity(intent);
            }
        });
    }

    private void updateView() {
        myListview = new MyListview(getActivity(),result);
        listView_tag.setAdapter(myListview);

        tv_class.setText(result.get(currentList).getName());

        SimpleAdapter gridView_class_adapter = new SimpleAdapter(getActivity(),class_data, R.layout.listview_class,
                new String[]{"name"}, new int[]{R.id.btn_class});
        gridView_class.setAdapter(gridView_class_adapter);
    }

    private void initData() {

        //创建哈希表用于创建适配器
        class_data = new ArrayList<HashMap<String,Object>>();
        Log.i("initData",currentList+"");
        for(RecipeClassResultBean.ResultBean.ListBean listBean : result.get(currentList).getList()){
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put("classid",listBean.getClassid());
            item.put("name", listBean.getName());
            item.put("parentid",listBean.getParentid());
            class_data.add(item);
        }
        Bundle bundle = getArguments();
        if (bundle!=null){
            login_state = bundle.getBoolean("loginstate");
            user = bundle.getParcelable("user");
        }
    }

    //初始化视图
    public void initView(View view){
        listView_tag = view.findViewById(R.id.listview_tag_container);
        gridView_class = view.findViewById(R.id.gridview_class_container);
        tv_class = view.findViewById(R.id.tv_class);
    }

    class getData extends AsyncTask{

        @Override
        protected RecipeClassResultBean doInBackground(Object[] params) {
            String uripath = ResourceDao.recipeClassUrl+"appkey="+ResourceDao.appkey;
            Log.i("initData.Thread","uri构建完毕"+uripath);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5000, TimeUnit.SECONDS)
                    .readTimeout(5000,TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(uripath)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()){
                    String result = response.body().string();
                    Gson gson = new Gson();
                    RecipeClassResultBean resultBean = gson.fromJson(result,RecipeClassResultBean.class);
                    Log.i("Fragment_kind.initData","数据获取结束...");
                    return resultBean;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            RecipeClassResultBean recipeClassResultBean = (RecipeClassResultBean) o;
            if (recipeClassResultBean!=null){
                Log.i("Fragment.onPostExecute",recipeClassResultBean.getMsg());
                result = recipeClassResultBean.getResult();
                initData();
                updateView();
            }
        }
    }


    public class MyListview extends BaseAdapter {
        private LayoutInflater inflater;
        private List<RecipeClassResultBean.ResultBean> result;
        public MyListview(Context context, List<RecipeClassResultBean.ResultBean> result) {
            this.inflater = LayoutInflater.from(context);
            this.result = result;
        }
        @Override
        public int getCount() {
            return this.result.size();
        }

        @Override
        public Object getItem(int position) {
            return result.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.listview_tag, null);
                holder = new ViewHolder();
                holder.tv_line = convertView.findViewById(R.id.tv_line);
                holder.tv_tagname = convertView.findViewById(R.id.tv_tagname);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv_tagname.setText(result.get(position).getName());
            if (currentList == position){
                holder.tv_tagname.setTextColor(getResources().getColor(R.color.theme));
                holder.tv_tagname.setBackgroundColor(getResources().getColor(R.color.white));
                holder.tv_line.setBackgroundColor(getResources().getColor(R.color.theme));
            } else {
                holder.tv_tagname.setTextColor(getResources().getColor(R.color.black));
                holder.tv_line.setBackgroundColor(getResources().getColor(R.color.crystal));
            }
            return convertView;
        }
        public class ViewHolder {
            public TextView tv_line;
            public TextView tv_tagname;
        }
    }
}
